<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      destroy-on-close
      draggable
      @open="handleOpen"
      @close="handleClose"
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>历史申请</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <el-card class="w-full pt-[5px] pb0">
        <el-form :model="searchForm" class="mt-[20px]" label-width="96px" ref="searchFormRef">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="searchForm.projectName" placeholder="项目名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="申请人" prop="applierName">
                <el-input v-model="searchForm.applierName" placeholder="申请人" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="" label-width="0">
                <el-input
                  v-model="searchForm.minFee"
                  placeholder="最小项目总经费"
                  clearable
                  style="width: calc(50% - 10px)"
                />
                <span style="width: 20px; text-align: center">至</span>
                <el-input
                  v-model="searchForm.maxFee"
                  placeholder="最大项目总经费"
                  clearable
                  style="width: calc(50% - 10px)"
                  class="mb-[0px]"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="flex justify-end">
                <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
                  >更多
                  <el-icon color="#fff">
                    <CaretTop v-show="searchFormOpen" />
                    <CaretBottom v-show="!searchFormOpen" />
                  </el-icon>
                </el-button>
                <el-button type="primary" @click="state.search">查询</el-button>
                <el-button @click="resetForm">重置</el-button>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-show="searchFormOpen">
            <el-col :span="6">
              <el-form-item label="申请日期">
                <el-date-picker
                  v-model="searchForm.applyDate1"
                  type="year"
                  value-format="YYYY"
                  style="width: calc(50% - 10px)"
                />
                <span style="width: 20px; text-align: center">至</span>
                <el-date-picker
                  v-model="searchForm.applyDate2"
                  type="year"
                  value-format="YYYY"
                  style="width: calc(50% - 10px)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="立项状态" prop="lixiangState">
                <CustomTreeSelect
                  :isFetch="false"
                  :dataList="lxStatusList.value"
                  placeholder="立项状态"
                  v-model="searchForm.lixiangState"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="所属单位" prop="unitIds">
                <CustomTreeSelect
                  :dataList="unitList.value"
                  placeholder="所属单位"
                  v-model="searchForm.unitIds"
                  valueKey="codeColumn"
                  labelKey="valueColumn"
                  :isFetch="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目编号" prop="projectCode">
                <el-input v-model="searchForm.projectCode" placeholder="项目编号" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="一级学科" prop="level1Subjects">
                <CustomTreeSelect
                  paramsName="一级学科"
                  placeholder="一级学科"
                  v-model="searchForm.level1Subjects"
                  valueKey="id"
                  labelKey="label"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="关键词" prop="keyword">
                <el-input v-model="searchForm.keyword" placeholder="关键词" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="审核状态" prop="applyState">
                <CustomTreeSelect
                  placeholder="审核状态"
                  v-model="searchForm.applyState"
                  valueKey="dictValue"
                  labelKey="dictLabel"
                  :isFetch="false"
                  :dataList="checkStatusList.value"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card class="w-full pt-[5px] mt-[10px]">
        <div class="mb-[20px]">
          <el-button @click="handleDelSelect">
            <el-icon class="mr-[5px]"><DeleteFilled /></el-icon>
            删除
          </el-button>
          <el-button @click="handleExport">
            <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
          </el-button>
        </div>
        <el-table
          :data="state.tableData"
          class="w-full"
          stripe
          row-key="id"
          v-loading="state.loading"
          ref="tableRef"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="项目名称">
            <template #default="{ row }">
              <el-link type="primary" @click="handleShow(row.id)">{{ row.name }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="applierName" label="申请人" />
          <el-table-column prop="applyFee" label="申请经费（万元）" />
          <el-table-column label="申请日期">
            <template #default="{ row }">
              <DateLabel :value="row.applyDate" />
            </template>
          </el-table-column>
          <el-table-column prop="lixiangState" label="立项状态">
            <template #default="{ row }">
              <CommonLabel :dataList="lxStatusList.value" :value="row.lixiangState" />
            </template>
          </el-table-column>
          <el-table-column prop="unitId" label="所属单位">
            <template #default="{ row }">
              <CommonTreeLabel
                :dataList="unitList.value"
                valueKey="codeColumn"
                labelKey="valueColumn"
                :value="row.unitId"
              />
            </template>
          </el-table-column>
          <el-table-column prop="checkState" label="审核状态">
            <template #default="{ row }">
              <CommonLabel
                :dataList="checkStatusList.value"
                valueKey="dictValue"
                labelKey="dictLabel"
                :value="row.checkState"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" plain @click="handleProject(row.applierId)">
                查看已参与项目
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="mt-[20px] flex justify-end">
          <el-pagination
            v-bind="state.pagination"
            @update:current-page="state.currentChange"
            @update:page-size="state.sizeChange"
          />
        </div>
      </el-card>
    </el-dialog>
    <ViewModal ref="viewModalRef" v-if="viewModalVisible" />
    <HistoryJoinModal ref="historyJoinModalRef" />
    <exportModal
      v-model="exportVisible"
      :selectList="exportFieldList"
      :title="exportTitle"
      @callBack="handleSelectOk"
    />
  </div>
</template>

<script setup>
import useTable from "@/hooks/useTable";
import ViewModal from "@/views/project/xj/sbxm/sbcl/components/ViewModal.vue";
import HistoryJoinModal from "./HistoryJoinModal.vue";
import { getHistoryData, exportHistoryRecords } from "@/api/project/xj/sbxm";
import { exportFields } from "@/api/project/xj/sbxm/sbcl";
import { delRecords } from "@/api/project/xj/sbxm/sbcl";
import DateLabel from "@/views/project/components/DateLabel.vue";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import CommonTreeLabel from "@/views/project/components/CommonTreeLabel.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import exportModal from "@/components/export";
import { downloadFile } from "@/utils/main";
import useCommonFetch from "@/hooks/useCommonFetch";
import useDictFetch from "@/hooks/useDictFetch";
import { ElMessage } from "element-plus";
const unitList = ref([]);
const lxStatusList = ref([]);
const checkStatusList = ref([]);
const searchFormOpen = ref(false);
const searchFormRef = ref();
const tableRef = ref();
const viewModalRef = ref();
const viewModalVisible = ref(false);
const historyJoinModalRef = ref();
const dialogVisible = ref(false);
const exportVisible = ref(false);
const exportFieldList = ref([]);
const exportTitle = "申报材料";
const searchForm = ref({
  projectName: "",
  applierName: "",
  minFee: "",
  maxFee: "",
  applyDate1: "", //申请时间
  applyDate2: "",
  lixiangState: [], //立项状态
  unitIds: [], //所属单位
  projectCode: "", //项目编号
  level1Subjects: [], //一级学科
  keyword: "",
  applyState: [], //审核状态
});
const state = ref({
  loading: false,
  pagination: null,
  sizeChange: null,
  currentChange: null,
  tableData: [],
  search: null,
  handleDelete: null,
});
//查看
const view = () => {
  dialogVisible.value = true;
  state.value = useTable((pagin) =>
    getHistoryData({
      pageNum: pagin.pageNum,
      pageSize: pagin.pageSize,
      ...searchForm.value,
    })
  );
};
defineExpose({ view });
//点击名称查看
const handleShow = (id) => {
  viewModalVisible.value = true;
  nextTick(() => {
    viewModalRef.value.view(id);
  });
};
//点击历史参与项目
const handleProject = (applierId) => {
  historyJoinModalRef.value.view(applierId);
};
//批量删除
const handleDelSelect = () => {
  //获取当前选中行
  const selectRows = tableRef.value.getSelectionRows();
  if (!selectRows.length) {
    ElMessage({
      message: "请选择要删除的数据！",
      type: "warning",
    });
    return;
  }
  const ids = selectRows.map((item) => item.id);
  const params = {
    ids,
  };
  state.handleDelete(delRecords, params);
};
//获取导出字段
const getExportFileds = async () => {
  try {
    const params = {
      page: "apply",
    };
    const res = await exportFields(params);
    if (res.code == 200) {
      const defaultCheckedList = [
        "projectName",
        "applierName",
        "projectTypeCode",
        "applyFee",
        "projectState",
        "unitName",
      ];
      res.data.forEach((item) => {
        exportFieldList.value.push({
          lable: item.showName,
          value: item.field,
          isSelect: defaultCheckedList.includes(item.field) ? true : false,
        });
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//点击导出按钮
const handleExport = async () => {
  //exportFieldList为空时才获取数据
  if (!exportFieldList.value.length) {
    await getExportFileds();
  }
  exportVisible.value = true;
};
//导出字段选择完毕
const handleSelectOk = async (val) => {
  const cols = val.map((item) => item.prop);
  try {
    const params = {
      ...searchForm.value,
      cols,
    };
    const res = await exportHistoryRecords(params);
    if (res.type != "application/json") {
      downloadFile(res, exportTitle + ".xlsx");
    }
  } catch (error) {
    console.log(error);
  }
};
const handleOpen = () => {
  unitList.value = useCommonFetch("成果归属单位");
  lxStatusList.value = useCommonFetch("立项状态");
  checkStatusList.value = useDictFetch("bpm_process_instance_status"); //审核状态
};
const handleClose = () => {
  searchFormRef.value.resetFields();
  searchForm.value.minFee = "";
  searchForm.value.maxFee = "";
  searchForm.value.applyDate1 = "";
  searchForm.value.applyDate2 = "";
};
//点击重置
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value.minFee = "";
  searchForm.value.maxFee = "";
  searchForm.value.applyDate1 = "";
  searchForm.value.applyDate2 = "";
  state.value.search();
};
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
:deep(.el-dialog__body) {
  padding-bottom: 0;
}
</style>
